package facade;

import java.util.ArrayList;
import java.util.List;


import javax.persistence.*;

import Entidade.Material;
import VO.MaterialVO;

public class FacedeMaterialImpl implements FacadeMaterial {

	public static String entidade ="sistemaDarlan";
	
	public MaterialVO buscamaterial(Integer id) {
		Material m = new Material();
		MaterialVO vo = new MaterialVO();
		
		 try{
			  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
			manager.getTransaction().begin();
		     m = (Material) manager.find(Material.class,id);
		     
		     vo.setAnexo(m.getAnexo());
		     vo.setDescricao(m.getDescricao());
		     vo.setId(m.getId());
		     vo.setNome(m.getNome());
		    
		    manager.getTransaction().commit();
		    manager.close();
		    
		    return vo;
		  }catch  (Exception e){
			    e.getMessage();
			
		  }
		
	
		return null;
	}


	public void salvar(MaterialVO vo) {

		Material m = new Material();
		m.setAnexo(vo.getAnexo());
		m.setDescricao(vo.getDescricao());
		m.setNome(vo.getNome());
		
		
	  try{
		  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
		manager.getTransaction().begin();
	  
	    manager.persist(m);
	
	    manager.getTransaction().commit();
	    manager.close();
	    
	  }catch  (Exception e){
		    e.getMessage();
		
	  }
		
	}

	public List<MaterialVO> buscaTodosMateriais() {
		
		try{
		    EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
			Query q = manager.createQuery("from Material f");
		
			List<MaterialVO>  mVo= new ArrayList<MaterialVO>(); 
			
			List<Material> resultList =q.getResultList();
			
			for(Material m : resultList){
				
				MaterialVO vo = new MaterialVO();
				vo.setAnexo(m.getAnexo());
				vo.setDescricao(m.getDescricao());
				vo.setNome(m.getNome());
				vo.setId(m.getId());
				
				mVo.add(vo);
			}
				
			
			
			return mVo;
			
		}catch (Exception e){
			e.getMessage();
		}
		
		return null;
	}


	public void excluirMaterial(MaterialVO vo) throws TrataErroPersistecia {
		Material m = new Material();
		 try{
			  EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();
		     manager.getTransaction().begin();
		     
		   
		    m = manager.find(Material.class,vo.getId());
		     
		     
		     manager.merge(m);
		     manager.remove(m);
		   
		    manager.getTransaction().commit();
		    manager.close();
		    
		  
		  }catch  (Exception e){
			    e.getMessage();
			
		  }
		
		
	}

}
